
#include "SvrNetRPSession.h"
#include "SvrNetSessionMan.h"
#include "TGSvrNetMan.h"

bool SvrNetSessionMan::AnchorLogined(DWORD nID)
{
	DD_AUTO_LOCK xLock(&m_xSessionSect);
	SvrNetRPSession*  pSession = SessionHead ;
	while (NULL != pSession )
	{
		if( pSession->m_bUse && pSession->GetAnchorID() == nID)
		{
			return true ;
		}
		pSession = pSession->next ;
	}
	return false ;
}

SvrNetRPSession*  SvrNetSessionMan::AddSession(TGSvrNetMan *pSvrNet,TG_ANCHOR_INFO* pAnchorInfo)
{
	unsigned int nCount ;
	DD_AUTO_LOCK xLock(&m_xSessionSect);
	SvrNetRPSession*  pSession = SessionHead ;
	while (NULL != pSession )
	{
		if( !pSession->m_bUse )
		{
			if (pSession->GetAnchorID() == pAnchorInfo->dwUserID)
			{
				break ;
			}
			else
			{				
				pSession->GetItemCount(nCount);
				if (nCount == 0)
				{
					break ;
				}
			}			
		}
		pSession = pSession->next ;
	}
	if (pSession==NULL)
	{
		pSession = new SvrNetRPSession(pSvrNet);
		if (SessionHead==NULL)
		{
			SessionHead = pSession ;
			SessionTail = pSession ;
		}
		else
		{
			pSession->prev = SessionTail ;
			SessionTail->next = pSession ;
			SessionTail = SessionTail->next ;
		}
	}

	xLock.CancelLock() ;
	
	if(pSession->GetAnchorID() > 0)
	{
		pSession->ReInitialize();
	}
	else
	{
		pSession->Initialize();
	}
	pSession->SetAnchorInfo(pAnchorInfo);
	
	return pSession;
}

int SvrNetSessionMan::GetSessionCount()
{
	int nCount = 0 ;
	DD_AUTO_LOCK xLock(&m_xSessionSect);
	SvrNetRPSession*  pSession = SessionHead ;
	while (NULL != pSession)
	{
		if(pSession->m_bUse )
		{
			nCount++;
		}
		pSession = pSession->next ;
	}
	return nCount ;
}

int SvrNetSessionMan::GetAnchorList(unsigned char* pList ,int &nCount)
{
	int nCnt = 0 ;
	DD_AUTO_LOCK xLock(&m_xSessionSect);
	SvrNetRPSession*  pSession = SessionHead ;
	int   pos = 0 ;
	DWORD dwID ;
	while (NULL != pSession)
	{
		if(pSession->m_bUse )
		{
			memcpy(pList+pos,pSession->GetAnchorName(),TG_USERNAME_LEN); pos += TG_USERNAME_LEN ;
			dwID = pSession->GetAnchorID() ;
			memcpy(pList+pos,&dwID,sizeof(DWORD));	 pos += sizeof(DWORD) ;
			nCnt++;
		}
		if (nCnt == nCount)
		{
			return nCnt ;
		}
		pSession = pSession->next ;
	}
	nCount = nCnt ;
	return nCount ;
}